package com.mobeedom.android.justinstalled.db;

import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.mobeedom.android.justinstalled.R;

/**
 * Database helper class used to manage the creation and upgrading of your database. This class also usually provides
 * the DAOs used by the other classes.
 */
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
	protected Context mContext;

	// name of the database file for your application -- change to something
	// appropriate for your app
	private static final String DATABASE_NAME = "justinstalled.db";
	// any time you make changes to your database objects, you may have to
	// increase the database version
	private static final int DATABASE_VERSION = DbVersion.VERSION;

	// the DAO object we use to access the Appuntamento table
	private Dao<InstalledAppInfo, Integer> daoInstalledAppInfo = null;
	private RuntimeExceptionDao<InstalledAppInfo, Integer> daoInstalledAppInfoRuntime = null;
	private Dao<DbVersion, Integer> daoDbVersion;

	private static final AtomicInteger usageCounter = new AtomicInteger(0);

	// we do this so there is only one helper
	private static DatabaseHelper helper = null;

	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);
		this.mContext = context;
	}

	public static synchronized DatabaseHelper getHelper(Context context) {
		if (helper == null) {
			helper = new DatabaseHelper(context);
		}
		usageCounter.incrementAndGet();
		return helper;
	}

	/**
	 * This is called when the database is first created. Usually you should call createTable statements here to create
	 * the tables that will store your data.
	 */
	@Override
	public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
		try {
			Log.i(DatabaseHelper.class.getName(), "onCreate");
			TableUtils.createTable(connectionSource, DbVersion.class);
			TableUtils.createTable(connectionSource, InstalledAppInfo.class);
			getDaoDbVersion().updateRaw("insert into dbversion (id, version) values(1, 0)");
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
			throw new RuntimeException(e);
		}
	}

	/**
	 * This is called when your application is upgraded and it has a higher version number. This allows you to adjust
	 * the various data to match the new version number.
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
		try {
			Log.i(DatabaseHelper.class.getName(), "onUpgrade oldVersion = " + oldVersion + " newVersion = "
					+ newVersion);

			List<String> updStatements = DbVersion.getAlters(oldVersion, connectionSource);
			for (String stm : updStatements) {
				getDaoDbVersion().executeRaw(stm);
			}
			// alter post ddl
			switch (oldVersion) {
			case 1:
//				List<InstalledAppInfo> lst = getDaoRecordingInfo().queryForAll();
//				for (InstalledAppInfo recordingInfo : lst) {
//					recordingInfo.setDateRecFromTime(recordingInfo.getTimeStart());
//					getDaoRecordingInfo().update(recordingInfo);
//				}
			}
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Can't update database", e);
			throw new RuntimeException(e);
		}
	}

	/**
	 * Returns the Database Access Object (DAO) for our Appuntamento class. It will create it or just give the cached
	 * value.
	 */
	public Dao<InstalledAppInfo, Integer> getDaoInstalledAppInfo() throws SQLException {
		if (daoInstalledAppInfo == null) {
			daoInstalledAppInfo = getDao(InstalledAppInfo.class);
		}
		return daoInstalledAppInfo;
	}

	/**
	 * Returns the RuntimeExceptionDao (Database Access Object) version of a Dao for our Appuntamento class. It will
	 * create it or just give the cached value. RuntimeExceptionDao only through RuntimeExceptions.
	 */
	public RuntimeExceptionDao<InstalledAppInfo, Integer> getDaoInstalledAppInfoRuntime() {
		if (daoInstalledAppInfoRuntime == null) {
			daoInstalledAppInfoRuntime = getRuntimeExceptionDao(InstalledAppInfo.class);
		}
		return daoInstalledAppInfoRuntime;
	}

	public Dao<DbVersion, Integer> getDaoDbVersion() throws SQLException {
		if (daoDbVersion == null) {
			daoDbVersion = getDao(DbVersion.class);
		}
		return daoDbVersion;
	}

	/**
	 * Close the database connections and clear any cached DAOs.
	 */
	@Override
	public void close() {
		if (usageCounter.decrementAndGet() == 0) {
			super.close();
			daoInstalledAppInfoRuntime = null;
			daoInstalledAppInfo = null;
			daoDbVersion = null;
		}
	}
}
